//
//  AppGlobal.m
//  XiaoMiao
//
//  Created by 23 on 2017/11/22.
//  Copyright © 2017年 smallyou. All rights reserved.
//

#import "AppGlobal.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

@implementation AppGlobal


+ (NSString *)currentVersion {
    return [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
}

+ (NSString *)appIconImageNamed {
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    return [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
}

#pragma mark - 用户模块
//////////////////////////////////用户模块//////////////////////////////////

/**获取网络状态*/
+ (YYReachabilityStatus)getNetworkStatus
{
    YYReachability* reachability  = [YYReachability reachability];
    YYReachabilityStatus status = reachability.status;

    return status;
}

/**更新登录状态*/
+ (void)updateLoginStatus:(BOOL)isLogin
{
    [[NSUserDefaults standardUserDefaults] setBool:isLogin forKey:kIsLoginKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/**判断是否登录*/
+ (BOOL)isLogin
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:kIsLoginKey];
}

/**退出*/
+ (void)logout
{
    //1 清除登录状态
    [self updateLoginStatus:NO];
    
    //2 清除账号信息
    [LoginInfoModel clearLoginInfo];
}

/**获取设备号*/
+ (NSString *)getDeviceToken
{
    return [[NSUserDefaults standardUserDefaults] stringForKey:kDeviceTokenKey];
}
/**更新设备号**/
+ (void)updateDeviceToken:(NSString *)DeviceToken
{
    [[NSUserDefaults standardUserDefaults] setObject:DeviceToken forKey:kDeviceTokenKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


/**获取会话id*/
+ (NSString *)getSid
{
    return [[NSUserDefaults standardUserDefaults] stringForKey:kSessionKey];
}

+ (void)updateSid:(NSString *)sid
{
    [[NSUserDefaults standardUserDefaults] setObject:sid forKey:kSessionKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

static NSString *const kLoginAccountKey = @"kLoginAccountKey";
+ (NSString *)getLoginAccount
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:kLoginAccountKey];
}
+ (void)updateLoginAccount:(NSString *)account
{
    [[NSUserDefaults standardUserDefaults] setObject:account forKey:kLoginAccountKey];
}
+ (void)clearLoginAccount
{
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kLoginAccountKey];
}


static NSString *const kLoginPwdKey = @"kLoginPwdKey";
+ (NSString *)getLoginPwd
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:kLoginPwdKey];
}
+ (void)updateLoginPwd:(NSString *)pwd
{
    [[NSUserDefaults standardUserDefaults] setObject:pwd forKey:kLoginPwdKey];
}
+ (void)clearLoginPwd
{
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kLoginPwdKey];
}


#pragma mark - 权限判断
//////////////////////////////////用户模块//////////////////////////////////


/**判断是否有相机权限*/
+ (BOOL)isCameraDeviceAvalableSureBlock:(void(^)(void))SureBlock
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted) {
        
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。" preferredStyle:UIAlertControllerStyleAlert];
        [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (SureBlock) {
                SureBlock();
            }
        }]];
        
        UIViewController *topRootViewController = [[UIApplication  sharedApplication] keyWindow].rootViewController;
        
        // 在这里加一个这个样式的循环
        while (topRootViewController.presentedViewController)
        {
            // 这里固定写法
            topRootViewController = topRootViewController.presentedViewController;
        }
        // 然后再进行present操作
        
        [topRootViewController presentViewController:alertVc animated:YES completion:nil];
        
        
        return NO;
    }
    
    return YES;
}

/**判断是否有相机权限*/
+ (BOOL)isCameraDeviceAvalable
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted) {

        return NO;
    }
    
    return YES;
}


/**判断是否有相册访问权限*/
+ (BOOL)isAssetsLibraryAvalable
{
    ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
    if (authStatus == ALAuthorizationStatusDenied || authStatus == ALAuthorizationStatusRestricted) {
        UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"无法使用相册" message:@"请在iPhone的\"设置-隐私-相册\"中允许访问相册" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
        
        return NO;
    }
    
    return YES;
}


//////////////////////////////////正则匹配//////////////////////////////////
/** 判断身份证是否是有效的 */
+ (NSString *)matchingIDCard:(NSString *)IDCard {
    if (IDCard.length != 18 && IDCard.length != 15) {
        return @"身份证不是15位或18位";
    }
    
    if (IDCard.length == 15) {
        NSScanner* scan = [NSScanner scannerWithString:IDCard];
        
        int val;
        BOOL isNum = [scan scanInt:&val] && [scan isAtEnd]; // 15位是否都是数字
        
        if (!isNum) {
            return @"15位身份证只能是数字";
            
        }else {
            // 15位身份证只做出生日期判断
            NSString *month = [IDCard substringWithRange:NSMakeRange(8, 2)];
            NSString *day = [IDCard substringWithRange:NSMakeRange(10, 2)];
            
            if ([month integerValue] > 12 || [month integerValue] == 0) {
                return @"身份证无效";
            }
            
            if ([day integerValue] > 32 || [day integerValue] == 0) {
                return @"身份证无效";
            }
            
            return nil;
        }
    }
    /***********  验证身份证上的年月日 *********/
    NSInteger year =  [[IDCard substringWithRange:NSMakeRange(6, 4)] integerValue];
    NSInteger month = [[IDCard substringWithRange:NSMakeRange(10, 2)] integerValue];
    NSInteger day =   [[IDCard substringWithRange:NSMakeRange(12, 2)] integerValue];
    
    
    if(year <= 1900 || year >= 2100){
        return @"身份证无效,请检查一下吧";
    }
    NSTimeZone *localZone = [NSTimeZone localTimeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setTimeZone:localZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *date = [dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d 12:01:01",year,month,day]];
    if (date == nil) {
        return @"身份证无效,请检查一下吧";
    }
    /***********************/
    NSArray *codeArray = @[@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6"
                           ,@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2"];
    
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner* scan02 = [NSScanner scannerWithString:[IDCard substringToIndex:17]];
    
    int val02;
    BOOL isNum02 = [scan02 scanInt:&val02] && [scan02 isAtEnd]; // 前17位是否都是数字
    
    if (!isNum02) {
        return @"身份证前17位不能包含字母";
    }
    
    int sumValue = 0;
    for (int i = 0; i < 17; i++) {
        sumValue += [[IDCard substringWithRange:NSMakeRange(i, 1) ] intValue] * [[codeArray objectAtIndex:i] intValue];
    }
    
    NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue % 11]];
    
    if ([strlast isEqualToString: [[IDCard substringWithRange:NSMakeRange(17, 1)] uppercaseString]]) {
        return nil;
    }
    
    return @"身份证无效,请检查一下吧";
}

+ (BOOL)isMatchingWithIdCard:(NSString *)idCard dobDate:(NSString *)dobDate {
    //
    NSString *dobFromIdCard = [idCard substringWithRange:NSMakeRange(6, 8)];
    
    //
    NSInteger year = [[dobDate substringToIndex:4] integerValue];
    NSInteger month =[[dobDate substringWithRange:NSMakeRange(5, 2)] integerValue];
    NSInteger day =[[dobDate substringFromIndex:8] integerValue];
    NSString *dobFromPersonDob = [NSString stringWithFormat:@"%ld%02ld%02ld", (long)year, (long)month, (long)day];
    
    if ([dobFromIdCard isEqualToString:dobFromPersonDob]) {
        return YES;
    }
    return NO;
}

/** 判断手机号码格式是否正确 */
+ (BOOL)isMatchingMobile:(NSString *)mobile {
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11) {
        return NO;
    }
    
    /**
     * 移动号段正则表达式
     */
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     * 联通号段正则表达式
     */
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     * 电信号段正则表达式
     */
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
    
    if (isMatch1 || isMatch2 || isMatch3) {
        return YES;
    }
    
    return NO;
}

@end
